package com.automapper.sqlbuilder.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.automapper.constants.ParameterConstants;
import com.automapper.exception.AutoMapperException;
import com.automapper.sqlbuilder.SqlBuilderTemplate;
import com.automapper.utils.FieldFacade;
import com.automapper.utils.ObjectFacade;
import com.automapper.utils.ParameterUtils;
import com.automapper.utils.PropertiesFacade;

public class UpdateSqlBuilder extends SqlBuilderTemplate {	
	
	private static final String VALUE = " %s = #{%s.%s} ";
	
	@Override
	public String buildSql(Object parameterObject, PropertiesFacade propertiesFacade) throws Exception {  
		AutoMapperException.NullRuntimeException(parameterObject, "Sorry,I refuse to build sql for a null object!"); 
		
		List<String> values = new ArrayList<>();
		Map<String, Object> parameterMap = (Map<String, Object>) parameterObject;
		//获取传入参数
		Object parameter = ParameterUtils.getParameter(parameterMap);
		
		String tableName = getTableName(parameterMap);
		ObjectFacade objectFacade = new ObjectFacade(parameter);
		List<String> columns = objectFacade.getColumnNames();
		this.filter(parameterMap, columns);
		
		StringBuilder tableSql = new StringBuilder();  
	    tableSql.append("update ").append(tableName).append(" set ");  
	    for (String column : columns) {
	    	FieldFacade fieldFacade = objectFacade.getFiledFacade(column);
	    	if (!fieldFacade.isBlank()) {
	    		values.add(String.format(VALUE, column, ParameterConstants.PARAM, objectFacade.getFiledFacade(column).getFieldName()));
	    	}	    	
	    }
	    tableSql.append(StringUtils.join(values, ","));  
	    tableSql.append(" where ");
	    tableSql.append(String.format(VALUE, objectFacade.getPrimaryKeyColumnName(), ParameterConstants.PARAM, objectFacade.getPrimaryKeyColumnName()));
	    
	    return tableSql.toString();
	}  
}
